use anyhow::Result;
use dioxus_logger::tracing::{error, info};
use reqwest::{Client, Response};
use serde::{Deserialize, Serialize};

use crate::global;

#[derive(Serialize, Deserialize, Debug)]
struct ResponseData<T> {
    data: T,
    errmsg: String,
    errno: i32,
}

#[derive(Serialize, Deserialize, Debug)]
struct LoginReq {
    account: String,
    password: String,
}

async fn post<T: Serialize>(client: &Client, payload: &T) -> Result<Response> {
    let url = "http://localhost:8000";

    let resp = client.post(url).json(payload).send().await?;

    Ok(resp)
}

pub async fn login(account: String, password: String) -> bool {
    let client = Client::new();
    let payload = LoginReq { account, password };

    match post(&client, &payload).await {
        Ok(resp) => {
            if resp.status().is_success() {
                let response: ResponseData<global::BzUser> = resp.json().await.unwrap();
                info!("User info response: {:?}", response);
                return true;
            }
            false
        }
        Err(err) => {
            error!("Error sending request: {}", err);
            false
        }
    }
}
